# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
from typing import List
from pydantic import TypeAdapter
from tortoise.expressions import Q

from hypertext import PagingResult
from common.utils.times import TimeUtil
from common.models.users import UserModel
from common.models.users import UserVisitorModel
from apps.admin.schemas.users import visitor_schema as schema


class VisitorService:
    """ 用户日志服务类 """

    @classmethod
    async def lists(cls, params: schema.VisitorSearchIn) -> PagingResult[schema.VisitorListVo]:
        """
        系统日志列表。

        Args:
            params (schema.VisitorSearchIn): 系统日志查询参数。

        Returns:
            PagingResult[schema.VisitorListVo]: 系统日志分页列表Vo。

        Author:
            zero
        """
        where = UserVisitorModel.build_search({
            "%like%": ["url"],
            "=": ["method", "ip"],
            "datetime": ["start_time|end_time@create_time"]
        }, params.__dict__)

        if params.user_sn:
            user = await UserModel.filter(sn=params.user_sn).first()
            if user:
                where.append(Q(user_id=user.id))
            else:
                where.append(Q(user_id=-1))

        _model = UserVisitorModel.filter(*where).order_by("-id")
        _pager = await UserVisitorModel.paginate(
            model=_model,
            page_no=params.page_no,
            page_size=params.page_size,
            fields=UserVisitorModel.without_field("params,endpoint,user_agent,start_time,end_time")
        )

        user_ids: List[int] = [item["user_id"] for item in _pager.lists if item["user_id"]]
        users = await UserModel.queryUserDictsById(user_ids)

        for item in _pager.lists:
            user = users.get(item["user_id"]) or {}
            item["nickname"] = user.get("nickname", "-")
            item["summary"] = item["summary"] if item["summary"] else "-"

        _pager.lists = [TypeAdapter(schema.VisitorListVo).validate_python(item) for item in _pager.lists]
        return _pager

    @classmethod
    async def detail(cls, id_: int) -> schema.VisitorDetailVo:
        """
        系统日志详细。

        Args:
            id_ (int): 日志ID。

        Returns:
            PagingResult[schema.JournalDetailVo]: 系统日志详情Vo。

        Author:
            zero
        """
        log = await UserVisitorModel.get(id=id_).values()

        if log["user_id"]:
            user = await UserModel.filter(id=log["user_id"]).first().values("nickname", "account")
            log["nickname"] = user.get("nickname", "")
            log["account"] = user.get("account", "")

        start_time = log["start_time"].split(".")
        end_time = log["end_time"].split(".")
        log["create_time"] = TimeUtil.timestamp_to_date(log["create_time"])
        log["start_time"] = TimeUtil.timestamp_to_date(int(start_time[0])) + "." + start_time[1]
        log["end_time"] = TimeUtil.timestamp_to_date(int(end_time[0])) + "." + end_time[1]

        return TypeAdapter(schema.VisitorDetailVo).validate_python(log)
